package com.fjec.market.schedule.handler;

import com.fjec.market.feign.UserClient;
import com.fjec.market.rabbitmq.provider.SysMsgProvider;
import com.fjec.market.service.IBizPhysicalOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class RemindOrderDeliveryHandler {

    @Resource
    private IBizPhysicalOrderService bizPhysicalOrderService;

    @Autowired
    private SysMsgProvider sysMsgProvider;

    @Autowired
    private UserClient userClient;

    @Value("${fjec.market.order.remind.deliver.time}")
    private Integer remindTime;

    public String handle() {
        // 查询出即将超时发货的订单
        List<Map<String, Object>> subOrders = bizPhysicalOrderService.getLongTimeUndeliveredOrders(remindTime);

        // todo: 去除重复发送消息
        subOrders.forEach(so -> {
            Long subOrderId = MapUtils.getLong(so, "subOrderId");
            Long buyerUserId = MapUtils.getLong(so, "buyerUserId");
            String spuName = MapUtils.getString(so, "spuName");
            String buyerName = MapUtils.getString(so, "buyerShopName");
            Map<String, Object> buyerOpenId = userClient.getOpenIdByUserId(buyerUserId);
            String openId = MapUtils.getString(buyerOpenId, "openId");

            Map<String, String> bizData = new HashMap<>();
            bizData.put("openId", openId);
            bizData.put("orderId", String.valueOf(subOrderId));
            bizData.put("spuName", spuName);
            bizData.put("remark", "距离发货时限已不足5小时，若已发货，请忽略");

            String title = "发货提醒";
            String content = String.format("用户%s向您采购%s，距离发货时限已不足5小时，请及时发货，若已发货，请忽略此提醒。", buyerName, spuName);
            sysMsgProvider.sendSysMessage(1, 9002, bizData, buyerUserId, title, content, 0L);
        });

        return "success";
    }
}
